//
//  Requestmanager.m
//  酷猫音乐
//
//  Created by lanou on 16/3/11.
//  Copyright © 2016年 阿伟. All rights reserved.
//

#import "Requestmanager.h"

@implementation Requestmanager
+(void)requestWithUrl:(NSString *)urlstring requesType:(RequestType )type parDic:(NSDictionary*)paDic finish:(finish)finish  error:(Error)error
{
    
    Requestmanager * requst = [[Requestmanager alloc]init];
    [requst requestWithUrl:urlstring requesType:type parDic:paDic finish:finish error:error];
    
}

-(void)requestWithUrl:(NSString *)urlstring requesType:(RequestType)requestType parDic:(NSDictionary *)parDic finish:(finish) finish error :(Error)error
{
        self.error = error;
       self.finish = finish;
    
    NSMutableURLRequest *  request =[NSMutableURLRequest requestWithURL:[NSURL URLWithString:urlstring]];
    NSURLSession * session = [NSURLSession sharedSession];
    
    if (requestType == requestTypePOST)
    {
        [request setHTTPMethod:@"POST"];
        if (parDic.count != 0)
        {
            [request setHTTPBody:[self dicToDataWithDic:parDic]];
        }
       
    }
    NSURLSessionDataTask * task = [session dataTaskWithRequest:request completionHandler:^(NSData * _Nullable data, NSURLResponse * _Nullable response, NSError * _Nullable error) {
        
        if (error) {
            self.error(error);
        }
        else
        {
    
            self.finish(data);
        }
    }];
    [task resume];
}


-(NSData*)dicToDataWithDic:(NSDictionary*)dic
{
    // 把字典里的键值对 按照key = value 拼接成字符串 然后 用&链接
    // 创建一个数组用来 装 每次拼接字符串
    NSMutableArray * array =[NSMutableArray array];
    for (NSString * key  in dic)
    {
        NSString * string = [NSString stringWithFormat:@"%@=%@",key,dic[key]];
        [array addObject:string];
    }
    NSString * datastring = [array componentsJoinedByString:@"&"];
    
    return [datastring dataUsingEncoding:NSUTF8StringEncoding];
}


@end
